class ReviewController < ApplicationController
  before_filter :before
  
  def edit
  end

  def update
    @review = Review.find(params[:id])
    @review.update_attributes(params[:review])
    @proposal = @review.proposal
    @reviews = Review.find(:all, :conditions => {:proposal_id => @proposal.id})
    if params[:commit] == "Entscheidung einreichen" 
      @review.status = "done"
    end
    
    if @review.save
      if Review.find(:first, :conditions => {:proposal_id => @proposal.id, :status => "open"}).nil?
        @proposal.status = "reviewed"
        @proposal.save
      end
      flash[:notice] = "Erfolgreich gespeichert"
      if @review.decision.nil?
        redirect_to "/review/show/" + @proposal.id.to_s
        flash[:error] = "Bitte Entscheid wählen!"
      else
        redirect_to "/review/show/" + @proposal.id.to_s

      end
      
    end
  end

  def show
    @open_reviews = Review.find(:all, :conditions => { :user_id => session[:user_id], :status => "open"})
    @done_reviews = Review.find(:all, :conditions => { :user_id => session[:user_id], :status => "done"})
    
    @proposal = Proposal.find(params[:id])
    @review = Review.find(:first, :conditions => { :user_id => session[:user_id], :proposal_id => @proposal.id})
    @documents = @proposal.documents.find(:all)
  end
  
  def index
    if params[:status].nil?
       params[:status] = "open"
    end
    @open_reviews = Review.find(:all, :conditions => { :user_id => session[:user_id], :status => "open"})
    @done_reviews = Review.find(:all, :conditions => { :user_id => session[:user_id], :status => "done"})
    if params[:status] == "done"
      @reviews = @done_reviews
    elsif params[:status] == "open"
      @reviews = @open_reviews
    end
    
    @proposals = Array.new
    @reviews.each do |review|
      @proposals << review.proposal
    end
    
    if @proposals.empty?
      flash.now[:notice]  = "Keine offenen Reviews"
    end
    
  end
    
  def before
    unless session[:user_id].nil?
      @user = User.find(session[:user_id])
      unless @user.role != ""
        flash[:error] = "Kein Zugriffsrecht"
        redirect_to "/"
      end
    else
      redirect_to "/"
    end
  end
  
  
end
